package com.qiujie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiujie.dto.Response;
import com.qiujie.dto.ResponseDTO;
import com.qiujie.entity.Dish;
import com.qiujie.entity.DishCategory;
import com.qiujie.mapper.DishMapper;
import com.qiujie.service.DishCategoryService;
import com.qiujie.service.DishService;
import com.qiujie.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 饮食Service实现类
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishCategoryService dishCategoryService;

    @Value("${file-path}")
    private String uploadPath;

    @Autowired
    private FileUtil fileUtil;

    @Override
    public ResponseDTO add(Dish dish) {
        // 检查分类是否存在
        DishCategory category = dishCategoryService.getById(dish.getCategoryId());
        if (category == null) {
            return Response.error("分类不存在");
        }
        
        // 检查饮食名称是否已存在
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName, dish.getName());
        if (this.count(queryWrapper) > 0) {
            return Response.error("饮食名称已存在");
        }
        
        dish.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        dish.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        dish.setDeleteFlag(0);
        dish.setStatus(1); // 默认在售
        
        boolean result = this.save(dish);
        return result ? Response.success() : Response.error("添加失败");
    }

    @Override
    public ResponseDTO update(Dish dish) {
        // 检查分类是否存在
        if (dish.getCategoryId() != null) {
            DishCategory category = dishCategoryService.getById(dish.getCategoryId());
            if (category == null) {
                return Response.error("分类不存在");
            }
        }
        
        // 检查饮食名称是否已存在(排除自身)
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName, dish.getName())
                    .ne(Dish::getId, dish.getId());
        if (this.count(queryWrapper) > 0) {
            return Response.error("饮食名称已存在");
        }
        
        dish.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        
        boolean result = this.updateById(dish);
        return result ? Response.success() : Response.error("更新失败");
    }

    @Override
    public ResponseDTO delete(Integer id) {
        // TODO: 检查饮食是否被引用(如在菜单中)
        
        boolean result = this.removeById(id);
        return result ? Response.success() : Response.error("删除失败");
    }

    @Override
    public ResponseDTO list(String name, Integer categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Dish::getName, name);
        }
        
        if (categoryId != null) {
            queryWrapper.eq(Dish::getCategoryId, categoryId);
        }
        
        // 按分类和更新时间排序
        queryWrapper.orderByAsc(Dish::getCategoryId).orderByDesc(Dish::getUpdateTime);
        
        List<Dish> list = this.list(queryWrapper);
        return Response.success(list);
    }

    @Override
    public ResponseDTO getDetail(Integer id) {
        Dish dish = this.getById(id);
        if (dish == null) {
            return Response.error("饮食不存在");
        }
        return Response.success(dish);
    }

    @Override
    public ResponseDTO updateStatus(Integer id, Integer status) {
        Dish dish = this.getById(id);
        if (dish == null) {
            return Response.error("饮食不存在");
        }
        
        dish.setStatus(status);
        dish.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        
        boolean result = this.updateById(dish);
        return result ? Response.success() : Response.error("更新状态失败");
    }

    @Override
    public ResponseDTO uploadImage(MultipartFile file) {
            try {
                // 上传图片
                String imagePath = fileUtil.upload(file, "menu");
                if (null == imagePath || "".equals(imagePath)) {
                    return Response.error("更新图片失败");
                } else {
                    return Response.success(imagePath);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Response.error("上传图片失败：" + e.getMessage());
            }
    }
} 